package com.mz.springbootdemo.common.filter;


import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 盟主
 * @Description 解决跨域问题
 * @createTime 2022年03月16日 17:26:00
 */
@WebFilter(filterName = "CorsFilter")
@Configuration
@Profile(value ={"dev","pro"})
public class CorsFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "OPTIONS, GET, POST, HEAD, PUT, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        /**
         * 根据情况可以具体约束请求头字段属性
         * response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,token,Cookie,Last-Modified, Authorization,tenantId,openId,JSESSIONID");
         */
        response.setHeader("Access-Control-Allow-Headers", "*");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}